package com.dhc.appbusinessfrm.business.login;

import com.dhc.appbusinessfrm.business.base.BaseBusinessImpl;
import com.dhc.appbusinessfrm.task.PriorityAsyncTask;
import com.dhc.appbusinessfrm.task.PriorityTask;
import com.dhc.appbusinessfrm.task.TaskLocker;
import com.dhc.appbusinessfrm.task.TaskPoolServer;
import com.dhc.appbusinessfrm.cache.StaticCacheStore;
import com.dhc.appbusinessfrm.model.ResultModel;
import com.dhc.appbusinessfrm.network.callback.NetTaskCallback;

import java.util.concurrent.Future;

import cn.com.hd.mall.web.webservices.entity.request.LoginUserRequest;
import cn.com.hd.mall.web.webservices.entity.response.LoginUserExt;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xy on 2015/6/12.
 */
public class LoginBusinessImpl extends BaseBusinessImpl implements LoginBusiness {

    @Override
    public Future login(final String loginName, final String password, final LoginCallback loginCallback) {

        return TaskPoolServer.ExecAsyncTask(new PriorityAsyncTask<ResultModel<LoginUserExt>>() {
            @Override
            public void onExecute(TaskLocker locker) {
                LoginUserRequest loginUserRequest = new LoginUserRequest();
                loginUserRequest.setLoginName(loginName);
                loginUserRequest.setPassword(password);
                danluNetInterface.login(loginUserRequest, new NetTaskCallback<ResultModel<LoginUserExt>>(getLocker()){

                    @Override
                    public void success(ResultModel<LoginUserExt> resultModel, Response response) {
                        super.success(resultModel, response);
                        // get response model
                        LoginUserExt loginUserExt = resultModel.getModel();
                        // callback to presenter
                        if(getBusinessHttpResult(resultModel)){
                            //save login info
                            preferenceUtils.setLoginNameAndPassword(loginUserExt.getLoginName(), loginUserExt.getPassword());
                            StaticCacheStore.getStaticCacheStoreInstance().setToken(loginUserExt.getToken());
                            loginCallback.netSuccess(resultModel);
                        }else {
                            loginCallback.netFailure(resultModel.getCode());
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        super.failure(error);
                        loginCallback.netFailure(getRetrofitErrorIndex(error));
                    }
                });
            }
        }.priority(PriorityTask.PRIORITY_ADVANCED));
    }

    public void testGit(){

    }

}
